package com.qf.controller;

import com.qf.service.AuthService;
import com.qf.util.CookieUtil;
import com.qf.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/*
 *@Description:授权
 *@author:刘哥
 *@Date:86180 2022/10/26 19:25
 */
@RestController
@RequestMapping("/auth")
public class LoginController {
    @Autowired
    private AuthService authService;

    @RequestMapping("/login")
    public String login(String userName, String password, HttpServletResponse response) {
//     校验用户名密码
        if (StringUtils.isEmpty(userName)) {
            return "用户名为空";
        }
        if (StringUtils.isEmpty(password)) {
            return "密码为空";
        }
        boolean flag = authService.login(userName, password);
        if (flag){
//        生成jwt秘钥,放入cookie中
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), userName, null);
            CookieUtil.addCookie(response,"localhost","/","token",token,-1,false);
            return token;
        }else {
            return "用户名或密码错误";
        }
    }
}
